package top.wilbert.collegelink.common.utils;/**
 * @author augus
 * @create 2023-03-10-16:06
 */

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.wilbert.collegelink.common.constant.PageConstant;
import top.wilbert.collegelink.common.xss.SQLFilter;

import java.util.Map;

/**
 * @ClassName:Query
 * @Description:
 * @author Augus
 * @date 2023/3/10 16:06
 * @Version 1.0
 **/
public class Query<T> {
    public IPage<T> getPage(Map<String, Object> params) {
        //分页参数
        long current = PageConstant.PAGE_NUM_DEFAULT;
        long size = PageConstant.PAGE_SIZE_DEFAULT;
        String orderField = PageConstant.ORDER_FIELD_DEFAULT;
        String order = PageConstant.PAGE_ORDER_DEFAULT;


        if (params.get(PageConstant.PAGE_NUM) != null) {
            current = Long.parseLong((String) params.get(PageConstant.PAGE_NUM));
        }
        if (params.get(PageConstant.PAGE_SIZE) != null) {
            size = Long.parseLong((String) params.get(PageConstant.PAGE_SIZE));
        }

        //分页对象
        Page<T> page = new Page<>(current, size);

        //分页参数
        params.put(PageConstant.PAGE_NUM, page);

        //排序字段
        //防止SQL注入（因为field、order是通过拼接SQL实现排序的，会有SQL注入风险）
        if(params.get(PageConstant.ORDER_FIELD) != null){
            orderField = SQLFilter.sqlInject((String) params.get(PageConstant.ORDER_FIELD));
        }
        if(params.get(PageConstant.ORDER) != null){
            order = (String) params.get(PageConstant.ORDER);
        }

        //前端字段排序
        if (PageConstant.PAGE_ORDER_DEFAULT.equalsIgnoreCase(order)) {
            return page.addOrder(OrderItem.desc(orderField));
        } else {
            return page.addOrder(OrderItem.asc(orderField));
        }
    }
}
